package cn.bjxy.javaks.store_ms.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;

import cn.bjxy.javaks.store_ms.entity.AdminEntity;
import cn.bjxy.javaks.store_ms.service.UIGoddsService;
import cn.bjxy.javaks.store_ms.service.UILogService;

import java.awt.FlowLayout;

public class MyFrame {

	private JFrame frame;

	private JPanel north;
	private static JRadioButton[] functions;

	private JSplitPane south;
	private JPanel southLeft;
	private JPanel southRight;
	private static JTable messages;
	private DefaultTableCellRenderer renderer;
	private static DefaultTableModel model;
	private JLabel[] labels;
	private static JTextField[] textFields;
	private JButton[] buttons;

	private ButtonGroup buttonGroup;

	private static AdminEntity adminEntity;
	private static JLabel userName;
	private JButton userInfor;
	private JButton exit;

	/**
	 * 主界面构造器
	 */
	public MyFrame() {
		initialize();
	}

	/**
	 * 主界面初始化
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setTitle("库存管理系统");
		frame.setBounds(100, 100, 1216, 694);
		frame.setLocationRelativeTo(null);// 居中显示
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[] { 800, 0 };
		gridBagLayout.rowHeights = new int[] { 100, 594 };
		gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
		gridBagLayout.rowWeights = new double[] { 0.0, 0.0 };
		frame.getContentPane().setLayout(gridBagLayout);

		initNorth();
		initSouth();

		frame.setVisible(true);
	}

	/**
	 * 初始化上界面
	 */
	private void initNorth() {
		north = new JPanel();
		north.setBorder(new TitledBorder(null, "选择", 0, 0, new Font("微软雅黑", Font.PLAIN, 14), Color.white));
		changeColor(north, 1);
		GridBagConstraints gbc_north = new GridBagConstraints();
		gbc_north.fill = GridBagConstraints.BOTH;
		gbc_north.insets = new Insets(0, 0, 5, 0);
		gbc_north.gridx = 0;
		gbc_north.gridy = 0;
		frame.getContentPane().add(north, gbc_north);
		north.setLayout(new BorderLayout(0, 0));

		JSplitPane northMid = new JSplitPane();
		northMid.setBorder(null);
		northMid.setDividerLocation(300);
		northMid.setDividerSize(0);
		north.add(northMid);

		JPanel northLeft = new JPanel();
		changeColor(northLeft, 1);
		northMid.setLeftComponent(northLeft);
		GridBagLayout gbl_northLeft = new GridBagLayout();
		gbl_northLeft.columnWidths = new int[] { 35, 73, 73, 73, 0 };
		gbl_northLeft.rowHeights = new int[] { 23, 0, 0 };
		gbl_northLeft.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
		gbl_northLeft.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
		northLeft.setLayout(gbl_northLeft);

		functions = new JRadioButton[2];
		String[] functionsNmae = { "浏览日志", "货物管理" };
		buttonGroup = new ButtonGroup();
		for (int i = 0; i < functions.length; i++) {
			functions[i] = new JRadioButton(functionsNmae[i]);
			functions[i].setFocusable(false);
			changeColor(functions[i], 1);
			GridBagConstraints gbc = new GridBagConstraints();
			gbc.anchor = GridBagConstraints.WEST;
			gbc.gridx = i + 1;
			gbc.gridy = 1;
			northLeft.add(functions[i], gbc);

			buttonGroup.add(functions[i]);
		}

		/* 开始默认选中货物管理 */
		functions[1].setSelected(true);
		functions[1].setEnabled(false);

		JPanel norhtRight = new JPanel();
		changeColor(norhtRight, 1);
		northMid.setRightComponent(norhtRight);
		norhtRight.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JLabel label = new JLabel("仓库库存管理系统");
		label.setForeground(Color.WHITE);
		label.setFont(new Font("微软雅黑", Font.PLAIN, 30));
		norhtRight.add(label);

		userName = new JLabel("您好，" + adminEntity.getName() + "     ");
		changeColor(userName, -1);
		norhtRight.add(userName);

		userInfor = new JButton("个人信息");
		userInfor.setFocusable(false);
		changeColor(userInfor, 1);
		norhtRight.add(userInfor);

		exit = new JButton("注销");
		exit.setFocusable(false);
		changeColor(exit, 1);
		norhtRight.add(exit);

		functionAddListener();
	}

	/**
	 * 初始化下界面
	 */
	private void initSouth() {
		south = new JSplitPane();
		south.setDividerSize(0);
		south.setEnabled(false);
		south.setBackground(new Color(25, 51, 64));
		GridBagConstraints gbc_middle = new GridBagConstraints();
		gbc_middle.insets = new Insets(0, 0, 5, 0);
		gbc_middle.fill = GridBagConstraints.BOTH;
		gbc_middle.gridx = 0;
		gbc_middle.gridy = 1;
		frame.getContentPane().add(south, gbc_middle);

		/**
		 * 刚进入界面 默认显示货物信息
		 */
		initCommonLeft(10,
				new String[] { "货物编号：", "货物名称：", "总库存：", "当前库存：", "购买者：", "备注：", "入库时间：", "出库时间：", "过期时间：", "修改时间：" });
		initCommonRight(new String[] { "货物编号", "货物名称", "总库存", "当前库存", "购买者", "备注", "入库时间", "出库时间", "过期时间", "修改时间" });

		/* 读取所有货物信息 */
		UIGoddsService.getAllGoods(false);
	}

	/**
	 * 初始化公用组件（左边）
	 * 
	 * @Count 生成Count个标签和输入框
	 * @labelNmae 标签内容
	 */
	private void initCommonLeft(int Count, String[] labelContxt) {
		southLeft = new JPanel();
		changeColor(southLeft, 2);
		southLeft.setBorder(new TitledBorder(null, "选择", 0, 0, new Font("微软雅黑", Font.PLAIN, 14), Color.white));
		south.setLeftComponent(southLeft);
		GridBagLayout gbl_left = new GridBagLayout();
		gbl_left.columnWidths = new int[] { 40, 145, 0 };
		gbl_left.rowHeights = new int[] { 0, 46, 46, 46, 46, 46, 45, 46, 46, 46, 46, 46, 0 };
		gbl_left.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
		gbl_left.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
				Double.MIN_VALUE };
		southLeft.setLayout(gbl_left);

		buttons = new JButton[4];
		String[] butonsName = { "添加", "删除", "修改", "重置" };

		for (int i = 0; i < 4; i++) {
			buttons[i] = new JButton(butonsName[i]);
			buttons[i].setFocusable(false);
			buttons[i].setBorder(null);
			changeColor(buttons[i], 2);

		}

		labels = new JLabel[Count];
		textFields = new JTextField[Count];

		for (int i = 0; i < Count; i++) {
			labels[i] = new JLabel();
			labels[i].setText(labelContxt[i]);
			changeColor(labels[i], -1);

			textFields[i] = new JTextField();
			changeColor(textFields[i], 2);
			textFields[i].setBorder(null);
			textFields[i].setCaretColor(Color.WHITE);

		}

		/* 修改时间不可输入 */
		textFields[Count - 1].setEditable(false);

		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.BOTH;

		/**
		 * index 用于取出数组元素 前两行两列为按钮
		 */
		int index = 0;
		for (int i = 0; i < 2; i++) {
			for (int j = 0; j < 2; j++) {
				gbc.gridx = j;
				gbc.gridy = i + 1;
				southLeft.add(buttons[index], gbc);
				index++;
			}
		}
		/* 第三行开始，第一列为标签 */
		/* 第一个标签和输入框不显示 */
		index = 1;
		for (int i = 3; index < labels.length; i++, index++) {
			gbc.gridx = 0;
			gbc.gridy = i;
			southLeft.add(labels[index], gbc);
		}
		/* 第二列为输入框 */
		index = 1;
		for (int i = 3; index < textFields.length; i++, index++) {
			gbc.gridx = 1;
			gbc.gridy = i;
			southLeft.add(textFields[index], gbc);
		}
		buttonsAddListener();
	}

	/**
	 * 初始化公用组件（右边）
	 * 
	 * @headerTile 列名
	 */
	private void initCommonRight(String[] headerTile) {
		southRight = new JPanel();
		southRight.setBorder(new TitledBorder(null, "信息", 0, 0, new Font("微软雅黑", Font.PLAIN, 14), Color.white));
		changeColor(southRight, 2);
		south.setRightComponent(southRight);
		southRight.setLayout(new BorderLayout(0, 0));

		messages = new JTable() {
			/* 表格不可编辑 */
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		changeColor(messages, 2);
		messages.getTableHeader().setBackground(new Color(25, 51, 64));
		messages.getTableHeader().setForeground(Color.WHITE);

		renderer = new DefaultTableCellRenderer();
		renderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
		messages.setDefaultRenderer(Object.class, renderer);

		model = new DefaultTableModel(null, headerTile);
		messages.setModel(model);

		messages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		messages.getTableHeader().setReorderingAllowed(false); // 不可整列移动
		messages.getTableHeader().setResizingAllowed(false); // 不可拉动表格
		southRight.add(messages);

		{
			/**
			 * 表格第一列默认隐藏
			 */
			TableColumn messagesColumn = messages.getTableHeader().getColumnModel().getColumn(0);
			messagesColumn.setMaxWidth(0);
			messagesColumn.setPreferredWidth(0);
			messagesColumn.setMinWidth(0);
			messagesColumn.setWidth(0);

			messages.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0);
			messages.getTableHeader().getColumnModel().getColumn(0).setMinWidth(0);
		}

		/* 为表头添加排序功能 */
		TableRowSorter sorter = new TableRowSorter(model);
		messages.setRowSorter(sorter);

		JScrollPane scrollPane = new JScrollPane(messages);
		changeColor(scrollPane.getVerticalScrollBar(), 2);
		southRight.add(scrollPane);

		MessageAddListner();
	}

	/**
	 * 单选按钮添加监听
	 */
	private void functionAddListener() {

		/* 浏览日志 */
		functions[0].addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				functions[0].setEnabled(false);
				functions[1].setEnabled(true);

				south.setDividerLocation(0);
				initCommonRight(new String[] { "日志编号", "操作管理员", "日志内容", "操作类型", "操作对象", "操作对象编号", "日志日期" });

				/* 读取所有日志信息 */
				UILogService.getAllLogs(false);
			}
		});

		/* 货物管理 */
		functions[1].addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				southLeft.removeAll();
				southRight.removeAll();

				functions[0].setEnabled(true);
				functions[1].setEnabled(false);
				initCommonLeft(10, new String[] { "货物编号：", "货物名称：", "总库存：", "当前库存：", "购买者：", "备注：", "入库时间：", "出库时间：",
						"过期时间：", "修改时间：" });
				initCommonRight(
						new String[] { "货物编号", "货物名称", "总库存", "当前库存", "购买者", "备注", "入库时间", "出库时间", "过期时间", "修改时间" });

				/* 读取所有货物信息 */
				UIGoddsService.getAllGoods(false);
			}
		});
	}

	/**
	 * 按钮添加鼠标监听
	 */
	private void buttonsAddListener() {

		userInfor.addMouseListener(new MouseAdapter() {
			/* 个人信息 */
			@Override
			public void mouseClicked(MouseEvent e) {
				System.out.println(this);
				new InforWindow(adminEntity, "MyFrame").setVisible(true);
			}
		});

		exit.addMouseListener(new MouseAdapter() {
			/* 注销 */
			@Override
			public void mouseClicked(MouseEvent e) {
				frame.dispose();
				new DengLuFrame();
			}
		});

		/* 添加 */
		buttons[0].addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				/* 选中货物管理 */
				if (UIGoddsService.goodsIsAdd(false))
					clearTextFields();
				else
					return;
			}
		});
		/* 删除 */
		buttons[1].addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				/* 获取要删除的管理员或者货物的ID */
				String deleteID = (String) model.getValueAt(messages.getSelectedRow(), 0);
				if (UIGoddsService.goodsIsDelete(deleteID)) {
					model.removeRow(messages.getSelectedRow());
					clearTextFields();
				} else
					return;
			}
		});
		/* 修改 */
		buttons[2].addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				if (UIGoddsService.goodsIsModify(false))
					clearTextFields();
				else
					return;
			}
		});
		/* 重置 */
		buttons[3].addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				for (int i = 0; i < textFields.length; i++) {
					textFields[i].setText(null);
				}
			}
		});
	}

	/**
	 * 添加表格的鼠标监听
	 */
	private void MessageAddListner() {
		messages.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				setData(messages.getSelectedRow());
			}
		});
	}

	/**
	 * 改变组件的背景颜色和字体颜色
	 * 
	 * @param compoent
	 * @param flag
	 */
	private void changeColor(Component compoent, int flag) {
		if (flag == 1) {
			compoent.setBackground(new Color(44, 89, 110));
		} else if (flag == 2) {
			compoent.setBackground(new Color(25, 51, 64));
		}
		compoent.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		compoent.setForeground(Color.WHITE);
	}

	/**
	 * 设置输入框的内容
	 * 
	 * @param SelectedRow
	 *            选中的行数
	 */
	private void setData(int SelectedRow) {
		for (int i = 0; i < textFields.length; i++) {
			textFields[i].setText((String) model.getValueAt(SelectedRow, i));
		}
	}

	/**
	 * 获得输入框的数据
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */
	public static String[] getData() {

		/* 选中货物管理 */
		String[] rowData = new String[10];/* 存储行数据 */
		for (int i = 0; i < 6; i++) {
			rowData[i] = textFields[i].getText();
		}
		rowData[6] = "2008-08-08 12:10:12";
		rowData[7] = "2009-01-01 13:13:13";
		rowData[8] = "20019-01-01 13:13:13";
		return rowData;
	}

	/**
	 * 添加表格信息
	 * 
	 * @param rowData
	 */
	public static void addRow(String[] rowData) {
		model.addRow(rowData);
	}

	/**
	 * 修改表格数据
	 * 
	 * @param rowData
	 */
	public static void modifyRow(String[] rowData) {
		/* 删除当前行，之后在该行插入一行新数据 */
		int currentRow = messages.getSelectedRow();
		model.removeRow(currentRow);
		model.insertRow(currentRow, rowData);
	}

	/**
	 * 清空输入框
	 */
	private void clearTextFields() {
		for (int i = 0; i < textFields.length; i++) {
			textFields[i].setText("");
		}
	}

	public static void setAdminEntity(AdminEntity Entity) {
		adminEntity = Entity;
	}

	public static AdminEntity getAdminEntity() {
		return adminEntity;
	}

	public static void setName(String name) {
		userName.setText("您好，" + name + "    ");
		System.out.println(name);
	}
}
